<?php

namespace App\Http\Logic\Api;

use Dcat\Admin\Traits\HasUploadedFile;
use Darabonba\OpenApi\Models\Config;
use Exception;

class UploadLogic
{
    use HasUploadedFile;

    /**
     * @throws Exception
     */
    public function upload($file): array
    {
        $disk = $this->disk('local');
        $config = config('upload');
        $dir = $config['types']['wechat']['dir'] ?? $config['default']['dir'];
        $md5_prefix = md5(uniqid());
        $newName = $md5_prefix . '.' . $file->getClientOriginalExtension();
        $path = "uploads/{$dir}/$newName";
        $disk->putFileAs($dir, $file, $newName);
        $exist = file_exists(public_path($path));
        if (!$exist) {
            throw new Exception('文件上传失败!');
        }

        return [
            'path' => $path,
            'name' => $file->getClientOriginalName(),
            'extname' => $file->getClientOriginalExtension(),
        ];
    }

    /**
     * @throws Exception
     */
    public function idCard($file)
    {
        $ali = new AliIdCard();
        $fileInfo = $this->upload($file);

        return $ali->info(public_path($fileInfo['path']));
    }

    public function delete($path){
        try{
            unlink(public_path($path));
        }catch (Exception $e){
            throw $e;
        }
    }
}
